<?php

/**
 * 易宠-货柜里
 * @author luoshumai
 */
namespace App\Service\VendorClient\ShopYiChong;
use Service\AppService\IdService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;

class ShopYiChongClient extends BaseService
{
    protected $clientConfig;

    public function __construct($apiBody = [])
    {
        $this->clientConfig = $apiBody;
    }

    /**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        $orderInfo      = $params['supplierOrder'];
        $orderItem      = $params['orderGoods'];
        $order          = $params['order'];
        $binfo          = $params['binfo'];

        //支付流水号
        $pay_sn    = $order['paySerial'] ?? $orderInfo['pay_sn'];

        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //优惠
        $discount_money = $orderInfo['discount_money'] < 0 ? - $orderInfo['discount_money'] : $orderInfo['discount_money'] ;

        //支付时间
        $pay_time       = date('Y-m-d H:i:s',$orderInfo['pay_time']);
        //支付流水号
        $pay_sn         = $orderInfo['pay_sn'];
        $order_sn       = $orderInfo['supplier_dsn'];


        //组装商品数据列表
        $goodsList          = [];
        $goodsTotalMoney    = 0;
        foreach ($orderItem as $key =>  & $item )
        {
            $price              = $item['price'];
            $spec_num           = $item['spec_num'];
            $quantity           = $item['quantity'];
            $singlePrice        = bcdiv((string)$price, (string)$spec_num,3);

            //不含税价格
            $goodsPrice         = bcdiv((string)$price, (string)$spec_num,3);
//            $goodsPrice         = bcmul((string)$goodsPrice,(string)100,1);
//            $goodsPrice         = bcdiv((string)ceil($goodsPrice), 100,2);


            $buyNum             = $spec_num * $quantity;
            $goodsTotalPrice    = bcmul((string)$goodsPrice,(string)$buyNum,2);

            //商品关税当前币种最小单位（分）
            $goodsCustomsTax    = bcsub((string)$singlePrice,(string)$goodsPrice,2);
            $taxAll             = bcmul((string)$goodsCustomsTax,(string)$buyNum,2);

            $goodsInfo = [
                "outer_sku"     => $item['barcode'],
                "title"         => $item['goods_name'],
                "price"         => (string)$goodsPrice,
                "num"           => $buyNum,
//                "dec_total"     => (string)$goodsTotalPrice,
            ];
            $goodsList[] = $goodsInfo;
            $goodsTotalMoney    = bcadd((string)$goodsTotalMoney,(string)$goodsTotalPrice,2);

        }

        //订单总价（商品保税价格 + 运费）
        $totalMoney             = bcadd((string)$goodsTotalMoney, (string)$deliver_money,2);
        //订单优惠金额
        $real_total_money       = $orderInfo['real_total_money'];
        $discount_money         = bcsub((string)$totalMoney,(string)$real_total_money,2);
        //创建订单数据
        $data = [
            "trade_no"                  => $order_sn,
            "buyer_nick"                => $orderInfo['buyer_realname'],
            'payment'                   => $real_total_money,
            'total_price'               => $totalMoney,
            'post_fee'                  => $deliver_money,
            'pay_type'                  => 1,
            'receiver'                  =>[
                'receiver_name'         =>$orderInfo['receive_name'],
                'receiver_province'     =>$orderInfo['province'],
                'receiver_city'         =>$orderInfo['city'],
                'receiver_area'         =>$orderInfo['district'],
                'receiver_mobile'       =>$orderInfo['recveive_phone'],
                'receiver_address'      =>$orderInfo['receive_address'],
            ],
            'buy_time'                  => date("Y-m-d H:i:s",$orderInfo['cd']),
            'pay_time'                  => date("Y-m-d H:i:s",time()),
            'goods'                     => $goodsList,
        ];
        $requestParam = [
            'method'    => 'orderCreate',
            'data'      => $data,
        ];
       return $this->execute($requestParam);
    }

    /**
     * 获取商品列表
     */
    public function queryGoodsList()
    {
        $data=[
            'current_page'     => $param['page'] ?? 1,
            'per_page'         => $param['limit'] ?? 20,
            "start_time"       => $param['start_time'] ?? "2020-01-01 00:00:00",
            'end_time'         => $param['end_time'] ?? "2022-12-31 00:00:00"
        ];
        $requestParam = [
            'method'    => 'goodsQuery',
            'data'      => $data,
        ];
        $responseParam=$this->execute($requestParam);
        if ($responseParam['code']!=Normal::SUC){
            return $responseParam;
        }
        $skuNos= array_column($responseParam['data']['data'],'goods_gid');
        //库存
        $stockList=$this->queryStock($skuNos);
        //媒体
        $mediaList=$this->queryMedia($skuNos);
        //组装数据
        foreach ($responseParam['data']['data'] as &$v){
            $v['stock']=$stockList['data'][$v['goods_gid']]??0;
            $v['media']=$mediaList['data'][$v['goods_gid']]??[];
            unset($v);
        }
        return $responseParam;
    }

    /**
     * 获取商品库存
     */
    public function queryStock($skuNos)
    {
        //创建订单数据
        $data = [
            "goods_gids" => $skuNos,
        ];
        $requestParam = [
            'method'    => 'queryStock',
            'data'      => $data,
        ];
        $stockListRes=$this->execute($requestParam);
        if ($stockListRes['code']!=Normal::SUC){
            return Normal::returnCode(Normal::SUC,'获取库存成功',[]);
        }
        return Normal::returnCode(Normal::SUC,'获取库存成功',array_column($stockListRes['data']['data'],'stock_num','goods_gid'));
    }

    /**
     * 获取商品库存
     */
    public function queryMedia($skuNos)
    {
        //创建订单数据
        $data = [
            "goods_gids" => $skuNos,
        ];
        $requestParam = [
            'method'    => 'queryMedia',
            'data'      => $data,
        ];
        $response=$this->execute($requestParam);
        if ($response['code']!=Normal::SUC){
            return Normal::returnCode(Normal::SUC,'获取图片成功',[]);
        }
        return Normal::returnCode(Normal::SUC,'获取图片成功',array_column($response['data']['data'],NULL,'goods_gid'));
    }


    /**
     * 获取sign参数
     */
    private function getSign( $param = [] )
    {
        ksort($param);
        $arr = [];
        foreach ($param as $k => $v) {
            if (is_array($v)) {
                $v = json_encode($v, JSON_UNESCAPED_UNICODE);
            }
            $arr[] = "{$k}{$v}";
        }
        $str = implode("", $arr);
        $str = $this->clientConfig['app_secret'].$str.$this->clientConfig['app_secret'];
        return strtoupper(bin2hex(md5($str,true)));
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        $method = $param['method'];
        $header = [
            "Content-Type: application/json;charset=utf-8",
        ];

        $data  = [
            'method'     => $this->clientConfig[$method],
            'app_id'     => $this->clientConfig['app_id'],
            'session_key'=> $this->clientConfig['sessionkey'],
            'version'    => '1.0',
            'format'     => 'json',
            'sign_method'=> 'MD5',
            'timestamp'  => date("Y-m-d H:i:s"),
            'body'       => json_encode($param['data'],JSON_UNESCAPED_UNICODE)
        ];
        $data['sign']   = $this->getSign($data);
        $url            = $this->clientConfig['baseurl'];
        $parameter = [
            [
                'tag'       => 'ShopYiChong_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $data,
                'method'    => 'post',
                'format'    => 'json',
                'header'    => $header,
            ],
        ];
        if( in_array($method,['goodsQuery','queryStock','queryMedia']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask    = current($resTask);
        $resHttp    = @json_decode($resTask['response']['result'], true);
        $errorMsg = $resHttp['message']??'请求失败';
        if( isset($resHttp['status_code']) && $resHttp['status_code'] == Normal::SUC ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        return Normal::returnCode(Normal::FAIL,$errorMsg);
    }
}
